if (typeof(tio) == "undefined") {
    tio = {};
}

tio.ws = {};

tio.ws = function ($, layim) {
    // 心跳超时时间，单位：毫秒
    this.heartbeatTimeout = 5000;
    // 心跳包发送间隔时间，单位：毫秒
    this.heartbeatSendInterval = this.heartbeatTimeout / 2;

    var self = this;

    /**
     * 建立连接
     */
    this.connect = function () {
        var url = "ws://localhost:9326?userId=" + self.mine.id;
        var socket = new WebSocket(url);
        self.socket = socket;

        // 建立ws连接
        socket.onopen = function () {
            console.log("----->tio ws connect");
            // 记录一下最后发送消息的时间
            self.lastInteractionTime(new Date().getTime());
            // 建立心跳
            self.ping();
        }
        // 关闭ws连接
        socket.onclose = function () {
            console.log("----->tio ws close");
            // 尝试重连
            self.reconn();
        }
        // 监听发送的消息
        socket.onmessage = function (res) {
            console.log("----->receive message：", res);
            var msgBody = eval('(' + res.data + ')');
            if (msgBody.emit === 'chatMessage') {
                layim.getMessage(msgBody.data);
            }
            self.lastInteractionTime(new Date().getTime());
        }
    }

    /**
     * 打开聊天窗口，获取个人信息
     */
    this.openChatWindow = function () {
        // 获取个人信息
        $.ajax({
            url: "/chat/getMineAndGroupData",
            async: false,
            success: function (res) {
                self.group = res.data.group;
                self.mine = res.data.mine;
            }
        });

        var cache =  layui.layim.cache();
        cache.mine = self.mine;
        // 打开窗口
        layim.chat(self.group);
        // 收缩聊天面板
        layim.setChatMin();
    }

    /**
     * 发送消息
     * @param res
     */
    this.sendChatMessage = function (res) {
        console.log("----->send chat message：", res);
        this.socket.send(JSON.stringify({
            type: 'chatMessage',
            data: res
        }));
    }

    /**
     * 初始化历史消息
     */
    this.initHistoryMessage = function () {
        localStorage.clear();
        $.ajax({
            url: '/chat/getGroupHistoryMsg',
            success: function (res) {
                var data = res.data;
                if(data.length < 1) {
                    return;
                }

                for (var i in data){
                    layim.getMessage(data[i]);
                }
            }
        });
    }

    /**
     * 记录最后发送消息的时间
     * @returns {any}
     */
    this.lastInteractionTime = function () {
        if (arguments.length == 1) {
            this.lastInteractionTimeValue = arguments[0]
        }
        return this.lastInteractionTimeValue
    }

    /**
     * 心跳
     */
    this.ping = function () {
        // 心跳定时器
        self.pingIntervalId = setInterval(function () {
            // 一段时间未发送消息则发送心跳消息
            var iv = new Date().getTime() - self.lastInteractionTime();
            if ((self.heartbeatSendInterval + iv) >= self.heartbeatTimeout) {
                console.log("----->send ping message");
                self.socket.send(JSON.stringify({
                    type: 'pingMessage',
                    data: 'ping'
                }));
            }
        }, self.heartbeatSendInterval);
    }

    /**
     * 重连
     */
    this.reconn = function () {
        // 先删除心跳定时器
        clearInterval(self.pingIntervalId);

        // 然后尝试重连
        self.connect();
    }

}